package com.gxa.teax.admin.advice;

import com.gxa.teax.admin.thread.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * 服务日志方面
 * @author wangpeng
 * @date 2022/07/19
 */
@SuppressWarnings("SpellCheckingInspection")
@Component
@Aspect
@Slf4j
public class ServiceLogAspect {

    @Pointcut(value = "execution(* com.gxa.teax.admin.service.impl.*.*(..))")
    public void pointCut(){}

    @Before(value = "pointCut()")
    public void before(JoinPoint joinPoint){
        // 记录操作业务类型和方法名
        // 先全部信息
        Signature signature = joinPoint.getSignature();

        //GoodsServiceImpl.seckill(..)
        String shortName = signature.toShortString();

        //public java.lang.Boolean com.gxa.eshop.portal.service.impl.GoodsServiceImpl.seckill(java.lang.Long)
        signature.toLongString();

        // seckill
        signature.getName();


        log.info("=======执行{}方法前记录=======",shortName);

        // 获取前台用户的信息: 从UserTHreadLocal中获取
        // 判断是否为空, 防止用户信息为空导致空指针
        if(!StringUtils.isEmpty(UserThreadLocal.get())){
            log.info("操作人信息:{}",UserThreadLocal.get().toString());
        }

        // 处理时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = format.format(new Date());
        log.info("操作时间:{}",dateString);

        // 记录参数
        Object[] args = joinPoint.getArgs();
        log.info("参数信息:{}", Arrays.toString(args));

    }

    @AfterReturning(pointcut = "pointCut()",returning = "result")
    public void afterReturn(Object result){
        log.info("执行结果:{}", result);
        log.info("=======执行完毕=======");
    }
}
